package com.open4a.openstudy.manager.oauth;

import com.alibaba.fastjson.JSON;
import com.open4a.openstudy.entity.OauthEntityDao;
import com.open4a.openstudy.entity.oauth.OauthEntity;
import com.open4a.openstudy.event.OauthEvent;
import com.open4a.openstudy.manager.api.ApiManager;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import common.db.GreenDaoManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by yangkuo02 on 2017/6/4.
 */

public class OauthManager {

    private static volatile OauthManager instance;

    public OauthManager() {
    }

    public static OauthManager getInstance() {
        if (instance == null) {
            synchronized (OauthManager.class) {
                if (instance == null) {
                    instance = new OauthManager();
                }
            }
        }
        return instance;
    }

    public boolean isAuth() {
        OauthEntityDao dao = GreenDaoManager.getInstance().getDaoSession().getOauthEntityDao();
        List<OauthEntity> entities = dao.loadAll();
        if (entities != null && !entities.isEmpty()
                && entities.get(0).getAccessToken() != null
                && !"".equals(entities.get(0).getAccessToken())) {
            return true;
        }
        return false;
    }

    public String getAccessToken() {
        OauthEntityDao dao = GreenDaoManager.getInstance().getDaoSession().getOauthEntityDao();
        List<OauthEntity> entities = dao.loadAll();
        if (entities == null || entities.isEmpty()) {
            return null;
        }
        return entities.get(0).getAccessToken();
    }

    public String getRefreshToken() {
        OauthEntityDao dao = GreenDaoManager.getInstance().getDaoSession().getOauthEntityDao();
        List<OauthEntity> entities = dao.loadAll();
        if (entities == null || entities.isEmpty()) {
            return null;
        }
        return entities.get(0).getRefreshToken();
    }

    public void refreshToken(boolean isForce) {
        String refreshToken = getRefreshToken();
        if (refreshToken == null || "".equals(refreshToken)) {
            return;
        }
        ApiManager.getInstance().oauth2Token(refreshToken, true, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                OauthEntity entity = JSON.parseObject(json, OauthEntity.class);
                OauthEntityDao dao = GreenDaoManager.getInstance().getDaoSession().getOauthEntityDao();
                dao.insertOrReplace(entity);
                EventBus.getDefault().post(new OauthEvent());
            }
        });
    }
}